/**
 * 佣金管理
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require('authorize');
    require("permission");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("plupload");
    var util = require("util");
    require("./service");
    var ui = require("ui");
    require("../intermediary_organ/imgpreview");
    require('global');

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'brokerageModule', 'ShowPreviewImg']);

    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/1/1', {templateUrl: 'daikan/not-approve.html', controller: 'Type1State1QueryController'})
            .when('/1/2', {templateUrl: 'daikan/not-offer.html', controller: 'Type1State2QueryController'})
            .when('/1/3', {templateUrl: 'daikan/offer.html', controller: 'Type1State3QueryController'})
            .when('/5/1', {templateUrl: 'renchou/not-approve.html', controller: 'Type5State1QueryController'})
            .when('/5/2', {templateUrl: 'renchou/not-offer.html', controller: 'Type5State2QueryController'})
            .when('/5/3', {templateUrl: 'renchou/offer.html', controller: 'Type5State3QueryController'})
            .when('/2/1', {templateUrl: 'chenjiao/not-approve.html', controller: 'Type2State1QueryController'})
            .when('/2/2', {templateUrl: 'chenjiao/not-offer.html', controller: 'Type2State2QueryController'})
            .when('/2/3', {templateUrl: 'chenjiao/offer.html', controller: 'Type2State3QueryController'})
            .when('/2/approve-fail', {
                templateUrl: 'chenjiao/approve-fail.html',
                controller: 'ApproveFailQueryController'
            })
            .otherwise({redirectTo: '/2/1'});
    }]);

    function TabsController($scope, baseData, search, filter, query) {
        $scope.baseData = baseData;
        $scope.search = search;
        $scope.filter = filter;
        // 初始化数据
        baseData.currentQueryService = search;
        setTimeout(function () {
            // setTimeout 为了让路由先完成，防止 dom 元素闪动
            $scope.$apply(function () {
                baseData.initData();
            });
        }, 10);

        $scope.changeTab = function (brokerageType, brokerageState) {
            if (brokerageType !== undefined) {
                baseData.brokerageType = brokerageType;
            }
            if (brokerageState !== undefined) {
                baseData.brokerageState = brokerageState;
            }
        };
    }

    app.controller('TabsController', ['$scope', 'baseData', 'search', 'filter', 'query', TabsController]);

    var uploader, deferred;

    function QueryController($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage, queryDetails) {
        $scope.baseData = baseData;
        $scope.query = query;
        $scope.search = search;
        $scope.filter = filter;
        $scope.brokerage = brokerage;

        $scope.$watch('query.isPopup',function(newValue,oldValue){
            //成交产品类型校验修正 如果当前项目佣金规则不是按“全部”设置，校验接收到的ERP成交产品类型与佣金规则中的成交产品类型是否匹配，如存在不匹配，触发弹窗。
            //默认路由到 佣金管理 > 个人佣金 > 成交佣金 > 未审定、  佣金管理 > 机构佣金 > 成交佣金 > 未审定


            if (newValue == '1' && $location.path() == '/2/1') {
                util.showDialog({
                    title: '提示',
                    content: '<p style="text-indent: 2em;margin-bottom:10px;">当前项目存在ERP交易产品类型与云客成交产品类型设置不一致，将导致相关交易无法自动计算佣金。</p><p style="text-indent: 2em;margin-bottom:10px;">如需按产品类型计算佣金，你可以：</p><p style="text-indent: 2em;margin-bottom:10px;">1 在云客中创建相同的产品类型，并加入佣金规则中；</p><p style="text-indent: 2em;margin-bottom:10px;">2 或将ERP成交产品类型与已有的云客产品类型关联绑定。</p>',
                    width: 400,
                    button: [
                        {
                            id: 'ok', value: '我知道了', callback: function () {
                        }
                        }, {
                            id: 'cancel', value: '前往修改', autofocus: true, callback: function () {
                                location.href = '/page/parameter_settings/project.shtml?token='+util.getToken()+'#/houses_param';
                            }
                        }
                    ]
                })
            }
        });
        //显示详情对话框
        $scope.onShowBrokerageDetails = function (record, dialog, dialogScope) {
            dialog.button([]);
            dialogScope.closeDialog = function () {
                dialog.close();
            };
            //获取详情信息
            queryDetails.query(record).then(function (res) {
                if (res && res.data && res.data.data) {
                    var data = res.data.data;
                    _.each(['card_img_b', 'card_img_a', 'bank_card_img', 'bank_name', 'bank_account', 'bank_sub_branch','city_name'], function (k) {
                        dialogScope.data[k] = data[k];
                    })
                }
            });
            dialogScope.baseData = $scope.baseData;
            dialogScope.brokerage = $scope.brokerage;
            dialogScope.detailOperation = function (data, whichbtn) {
                switch (whichbtn) {
                    case 1 ://审核通过
                        $scope.brokerage.dealApprove(data).then(function (res) {
                            if(res&&res.data&&res.data.retCode ==0 ){
                                ui.showSucTip();
                                dialog.close();
                            }
                        });
                        break;
                    case 2 ://审核不通过
                        $scope.brokerage.dealApproveFail(data).then(function (res) {
                            if(res&&res.data&&res.data.retCode ==0 ) {
                                ui.showSucTip();
                                dialog.close();
                            }
                        });
                        break;
                    case 3 ://取消审定
                        $scope.brokerage.cancelApprove(data).then(function (res) {
                            if(res&&res.data&&res.data.retCode ==0 ) {
                                ui.showSucTip();
                                dialog.close();
                            }
                        });
                        break;
                    case 4 ://发放
                        $scope.brokerage.dealOffer(data).then(function (res) {
                            if(res&&res.data&&res.data.retCode ==0 ) {
                                ui.showSucTip();
                                dialog.close();
                            }
                        });
                        break;
                    case 5 ://委托发放
                        if(brokerage.validateDealOffer(data)){
                            $scope.brokerage.dealPay(data).then(function (res) {
                                if(res&&res.data&&res.data.retCode ==0 ) {
                                    ui.showSucTip();
                                    dialog.close();
                                }
                            });
                        }
                        break;
                }
            }

        }

        $scope.initImport = function ($data) {
            if (uploader) {
                uploader.splice();
                uploader.setOption('url', '/api/index.php?r=qmyx/brokerage/import&brokerage_type=' + baseData.brokerageType + '&isAgency=' + baseData.isAgency + '&token=' + util.getToken());
                $('#import-name').text('');
                $('#import-state').text('');
            } else {
                uploader = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',

                    browse_button: $('#import').find('.btn')[0],
                    container: $('#import').find('.btn-group')[0],
                    multi_selection: false,
                    //chunk_size: '10kb',
                    file_data_name: 'filename',

                    filters: {
                        mime_types: [
                            {title: "Excel", extensions: "xls,xlsx"}
                        ],
                        prevent_duplicates: true //不允许选取重复文件
                    },

                    url: '/api/index.php?r=qmyx/brokerage/import&brokerage_type=' + baseData.brokerageType + '&isAgency=' + baseData.isAgency + '&token=' + util.getToken(),

                    // Flash settings
                    flash_swf_url: '/public/js/lib/plupload/Moxie.swf',

                    // Silverlight settings
                    silverlight_xap_url: '/public/js/lib/plupload/Moxie.xap',


                    init: {
                        FilesAdded: function (up, files) {
                            $('#import-name').text(files[0].name);
                            $('#import-state').text('');
                        },

                        UploadProgress: function (up, file) {
                            $('#import-state').text('导入中...');
                        },

                        Error: function (up, err) {
                            $('#import-state').text('上传出错');
                            var file = err.file;
                            var reason = err.message;
                            if (typeof console != 'undefined') {
                                // 程序上的错误在控制台输出
                                console.error('上传出错：' + reason);
                            }

                            if (deferred) {
                                deferred.reject(reason);
                            }
                        },

                        FileUploaded: function (up, file, info) {
                            var response = JSON.parse(info.response);
                            var state = '已上传 ';
                            var error = false;
                            if (response.retCode != '0') {
                                if (!response.errMsg) {
                                    state = '上传出错：错误代码（' + response.retCode + '）';
                                } else {
                                    state = '上传出错：' + response.errMsg;
                                }
                                error = true;
                            }

                            if (error) {
                                $('#import-state').text(state);
                                if (deferred) {
                                    deferred.reject(state);
                                }
                            }
                        },

                        UploadComplete: function () {
                            if (deferred) {
                                deferred.resolve();
                            }
                        }
                    }
                });

                uploader.init();
            }
        };

        $scope.importData = function () {
            if (!uploader.files.length) {
                util.alert('请选择要导入的文件');
                return false;
            }

            deferred = $q.defer();
            setTimeout(function () {
                uploader.start();
            }, 10);
            return deferred.promise.then(function () {
                baseData.query();
            });
        };

        if (!baseData.isAgency) {
            baseData.changeBrokerIdentity(undefined, '');
        }

        if (baseData.loaded) {
            query.data = [];
            baseData.currentQueryService.query();
        }

        $scope.confirmPass= function(item){
            util.confirm('确定审核通过吗？', {
                ok: function () {
                    brokerage.pass(item);
                }
            });
        };
    }

    // 带看未审定
    app.controller('Type1State1QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 1;
            baseData.brokerageState = 1;
            QueryController.apply(this, arguments);
        }]);

    // 带看待发放
    app.controller('Type1State2QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 1;
            baseData.brokerageState = 2;
            QueryController.apply(this, arguments);
        }]);

    // 带看已发放
    app.controller('Type1State3QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 1;
            baseData.brokerageState = 3;
            QueryController.apply(this, arguments);
        }]);

    // 认筹未审定
    app.controller('Type5State1QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 5;
            baseData.brokerageState = 1;
            QueryController.apply(this, arguments);
        }]);

    // 认筹待发放
    app.controller('Type5State2QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 5;
            baseData.brokerageState = 2;
            QueryController.apply(this, arguments);
        }]);

    // 认筹已发放
    app.controller('Type5State3QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 5;
            baseData.brokerageState = 3;
            QueryController.apply(this, arguments);
        }]);

    // 成交未审定
    app.controller('Type2State1QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage', 'queryDetails',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 2;
            baseData.brokerageState = 1;
            QueryController.apply(this, arguments);
        }]);

    // 成交待发放
    app.controller('Type2State2QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage', 'queryDetails',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 2;
            baseData.brokerageState = 2;
            QueryController.apply(this, arguments);
        }]);

    // 成交已发放
    app.controller('Type2State3QueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage', 'queryDetails',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 2;
            baseData.brokerageState = 3;
            QueryController.apply(this, arguments);
        }]);

    // 成交审核不通过
    app.controller('ApproveFailQueryController', ['$scope', '$routeParams', '$location', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage', 'queryDetails',
        function ($scope, $routeParams, $location, $q, query, search, filter, baseData, brokerage) {
            baseData.brokerageType = 2;
            baseData.brokerageState = 99;
            QueryController.apply(this, arguments);
        }]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});

